<template>
  <a-upload
    :name="name"
    :showUploadList="false"
    :multiple="multiple"
    :headers="tokenHeader"
    :action="action"
    v-bind="$attrs"
    @change="handleImportExcel"
  >
    <slot :loading="loading">
      <a-button :icon="icon" :loading="loading">导入</a-button>
    </slot>
  </a-upload>
</template>

<script>
export default {
  props: {
    action: {
      type: String,
      required: true
    },
    multiple: {
      type: Boolean,
      default: false
    },
    name: {
      type: String,
      default: 'file'
    },
    icon: {
      type: String,
      default: 'import'
    }
  },
  data() {
    return {
      loading: false
    }
  },
  methods: {
    handleImportExcel(info) {
      this.loading = info.file.status === 'uploading'
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let {
              message,
              result: { msg, fileUrl, fileName }
            } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: (
                <div>
                  <span>{msg}</span>
                  <br />
                  <span>
                    具体详情请{' '}
                    <a href={href} target="_blank" download={fileName}>
                      点击下载
                    </a>{' '}
                  </span>
                </div>
              )
            })
          } else {
            this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
          }
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}`)
        }
      } else if (info.file.status === 'error') {
        if (info.file.response.status === 500) {
          let data = info.file.response
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token && data.message.includes('Token失效')) {
            Modal.error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload()
                })
              }
            })
          }
        } else {
          this.$message.error(`文件上传失败: ${info.file.msg} `)
        }
      }
    }
  },
  computed: {
    //token header
    tokenHeader() {
      let head = { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) }
      let tenantId = Vue.ls.get(TENANT_ID)
      if (tenantId) {
        head['tenant-id'] = tenantId
      }
      return head
    }
  }
}
</script>

<style></style>
